package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.mall.order.dto.PayOrderSuccessRequest;
import com.cskaoyan.mall.order.dto.PayOrderSuccessResponse;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CancelOrderRequest;
import com.cskaoyan.order.dto.CancelOrderResponse;
import com.cskaoyan.order.dto.DeleteOrderRequest;
import com.cskaoyan.order.dto.DeleteOrderResponse;
import com.cskaoyan.order.service.OrderUpdateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

import static com.cskaoyan.order.constant.OrderConstants.*;

/**
 * @program: duolaimall
 * @description:
 * @author: Lexis
 * @create: 2022-05-20 22:20
 **/
@Service
public class OrderUpdateServiceImpl implements OrderUpdateService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    StockMapper stockMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Override
    public CancelOrderResponse cancelOrder(CancelOrderRequest request) {
        CancelOrderResponse response = new CancelOrderResponse();

        try {
            request.requestCheck();
            Order updateOrder = new Order();
            updateOrder.setUpdateTime(new Date());
            updateOrder.setOrderId(request.getOrderId());
            updateOrder.setCloseTime(new Date());
            updateOrder.setStatus(ORDER_STATUS_TRANSACTION_CANCEL);
            int rows = orderMapper.updateByPrimaryKeySelective(updateOrder);
            if (rows < 1) {
                throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(), OrderRetCode.DB_EXCEPTION.getMessage());
            }

            // 更新库存表
            Example example = new Example(OrderItem.class);
            example.createCriteria().andEqualTo("orderId", request.getOrderId());
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
            for (OrderItem orderItem : orderItems) {
                Integer num = orderItem.getNum();
                Stock stock = new Stock();
                stock.setItemId(orderItem.getItemId());
                stock.setStockCount(Long.valueOf(num));
                stock.setLockCount(-num);
                stockMapper.updateStock(stock);
            }

            // 更新库存状态
            orderItemMapper.updateStockStatus(STOCK_RELEASE, request.getOrderId());
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (BizException e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public DeleteOrderResponse deleteOrder(DeleteOrderRequest request) {
        DeleteOrderResponse response = new DeleteOrderResponse();

        try {
            request.requestCheck();
            String orderId = request.getOrderId();
            // 返还status为0的库存 更新库存表
            Order order = orderMapper.selectByPrimaryKey(orderId);

            if (order.getStatus() == ORDER_STATUS_INIT) {
                Example example = new Example(OrderItem.class);
                example.createCriteria().andEqualTo("orderId", request.getOrderId());
                List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
                for (OrderItem orderItem : orderItems) {
                    Integer num = orderItem.getNum();
                    Stock stock = new Stock();
                    stock.setItemId(orderItem.getItemId());
                    stock.setStockCount(Long.valueOf(num));
                    stock.setLockCount(-num);
                    stockMapper.updateStock(stock);
                }
            }

            // 删除订单物流表
            orderShippingMapper.deleteByPrimaryKey(request.getOrderId());

            // 删除订单关联表
            Example deleteExample = new Example(OrderItem.class);
            deleteExample.createCriteria().andEqualTo("orderId", request.getOrderId());
            orderItemMapper.deleteByExample(deleteExample);


            // 删除订单表
            orderMapper.deleteByPrimaryKey(request.getOrderId());
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public PayOrderSuccessResponse payOrderSuccess(PayOrderSuccessRequest request) {

        PayOrderSuccessResponse response = new PayOrderSuccessResponse();

        try {
            request.requestCheck();

            // 1. 判断订单的支付状态，如果订单已支付，直接返回，避免多次更新库存表
            Order orderStatus = orderMapper.selectByPrimaryKey(request.getOrderId());
            if (OrderConstants.ORDER_STATUS_PAYED == orderStatus.getStatus()) {
                response.setCode(OrderRetCode.SUCCESS.getCode());
                response.setMsg(OrderRetCode.SUCCESS.getMessage());
                return response;
            }

            // 2. 修改订单的状态 已支付状态
            Order order = new Order();
            order.setOrderId(request.getOrderId());
            order.setStatus(OrderConstants.ORDER_STATUS_PAYED);
            order.setUpdateTime(new Date());
            int updateRows = orderMapper.updateByPrimaryKeySelective(order);
            if (updateRows < 1) {
                throw new BizException(OrderRetCode.DB_EXCEPTION.getCode(), OrderRetCode.DB_EXCEPTION.getMessage());
            }
            Example example = new Example(OrderItem.class);
            example.createCriteria().andEqualTo("orderId", request.getOrderId());

            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);

            OrderItem orderItem = new OrderItem();
            orderItem.setStatus(OrderConstants.STOCK_CUT_SUCCESS);
            orderItemMapper.updateByExampleSelective(orderItem, example);
            // 3. 修改库存，根据订单id，查询出所有的订单商品条目，遍历订单商品条目，
            for (OrderItem item : orderItems) {

                //    根据订单商品条目购买的数量，去扣减对应商品锁定库存的数量
                Integer num = item.getNum();
                Stock stock = new Stock();
                stock.setItemId(item.getItemId());
                stock.setStockCount(0L);
                stock.setLockCount(-num);
                stockMapper.updateStock(stock);
            }
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (BizException e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }

        return response;
    }


}
